package org.wskyh.tcp;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Scanner;

public class TCPServer {
    public static void main(String[] args) throws IOException {
        ServerSocket serverSocket = new ServerSocket(8888);     // 服务端套接字
        ArrayList<Socket> clients = new ArrayList<>();      // 用于存放客户端套接字的集合

        // 发送消息线程
        new Thread(() -> {
            String request;
            Scanner scanner = new Scanner(System.in);
            try {
                OutputStream outputStream;
                String index = "1";
                Socket socket = null;
                do {
                    request = scanner.next();   // 获取请求消息

                    // 如果有多个客户端，则展示并让用户选择
                    if (clients.size() != 1) {
                        System.out.println("请选择要发送的客户端：");
                        // 遍历所有客户端的IP地址
                        for (int i = 0; i < clients.size(); i++) {
                            System.out.println(i + 1 + ". " + clients.get(i).getInetAddress());
                        }
                        System.out.println("*. 所有客户端");
                        index = scanner.next();
                    }

                    // 发送消息
                    if ("*".equals(index)) {
                        // 如果输入*，则发给所有人
                        for (Socket client : clients) {
                            outputStream = client.getOutputStream();
                            outputStream.write(request.getBytes());
                        }
                    } else {
                        // 否则发给特定的客户端
                        socket = clients.get(Integer.parseInt(index) - 1);
                        outputStream = socket.getOutputStream();
                        outputStream.write(request.getBytes());
                    }
                } while (!"exit".equals(request));
                // 关闭并移除socket
                if (socket != null) {
                    socket.close();
                    clients.remove(socket);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }).start();

        // 循环监听是否有客户端请求通信
        while (true) {
            Socket client = serverSocket.accept();      // 接收客户端套接字
            clients.add(client);
            // 接收信息
            new Thread(() -> {
                try {
                    InputStream inputStream = client.getInputStream();      // 获取输入流
                    byte[] bytes;
                    do {
                        // 循环读取和展示信息
                        bytes = new byte[1024];
                        inputStream.read(bytes);
                        System.out.println(client.getInetAddress() + "：" + new String(bytes));
                    } while (!"exit".equals(new String(Arrays.copyOf(bytes, 4))));
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }).start();
        }
    }
}